﻿

#include "Core/CollectableItem.h"

#include "Components/CapsuleComponent.h"
#include "PaperFlipbookComponent.h"
#include "Core/PlayerZDCharacter.h"
#include "Kismet/GameplayStatics.h"

ACollectableItem::ACollectableItem()
{
	PrimaryActorTick.bCanEverTick = true;

	CapsuleComponent = CreateDefaultSubobject<UCapsuleComponent>(TEXT("CapsuleComponent"));
	ItemFlipBook = CreateDefaultSubobject<UPaperFlipbookComponent>(TEXT("ItemFlipbook"));

	SetRootComponent(CapsuleComponent);
	ItemFlipBook->SetupAttachment(RootComponent);
}

void ACollectableItem::BeginPlay()
{
	Super::BeginPlay();

	CapsuleComponent->OnComponentBeginOverlap.AddDynamic(this, &ACollectableItem::OverlapBegin);
}

void ACollectableItem::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	const float Direction = sin(UGameplayStatics::GetTimeSeconds(GetWorld()) * 2);
	AddActorLocalOffset(FVector(0.0f, 0.0f, DeltaTime * Direction * FloatingSpeed));
}

void ACollectableItem::OverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
	UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	APlayerZDCharacter* Player = Cast<APlayerZDCharacter>(OtherActor);
	if (Player && Player->IsAlive)
	{
		Player->CollectItem(ItemType);
		Destroy();
	}
}

